package com.qiuzhiyi.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.InputFilter;
import android.text.InputType;
import android.view.View;

import com.bumptech.glide.Glide;
import com.li.utils.ImageUtil;
import com.li.utils.InputFilterUtil;
import com.li.utils.TransformUtil;
import com.li.utils.UriUtil;
import com.li.utils.VerifyUtil;
import com.li.widget.CircleImageView;
import com.li.widget.PersonalDetailItem;
import com.li.widget.TopNavigationBar;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.qiuzhiyi.R;
import com.qiuzhiyi.base.QZYBaseActivity;
import com.qiuzhiyi.cache.HumanCache;
import com.qiuzhiyi.dialogs.DateDialog;
import com.qiuzhiyi.item.BaseItem;
import com.qiuzhiyi.item.HumanItem;
import com.qiuzhiyi.net.ObservableHelper;
import com.qiuzhiyi.net.RetrofitHelper;
import com.qiuzhiyi.net.SelectorObserver;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Author: Li
 * Date: 2017/11/14 0014
 * Description: 个人信息界面
 */

public class PersonalInfoActivity extends QZYBaseActivity {

    private static final int REQUEST_CODE_CHOOSE = 0;
    private static final int REQUEST_CODE_PERMISSION = 241;
    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    //头像
    @BindView(R.id.img_head)
    CircleImageView mImgHead;
    //昵称
    @BindView(R.id.nick_name)
    PersonalDetailItem mNickName;
    //性别
    @BindView(R.id.sex)
    PersonalDetailItem mSex;
    //电话
    @BindView(R.id.phone)
    PersonalDetailItem mPhone;
    //出生年月
    @BindView(R.id.birth_date)
    PersonalDetailItem mBirthDate;
    //家乡
    @BindView(R.id.hometown)
    PersonalDetailItem mHometown;
    //签名
    @BindView(R.id.sign)
    PersonalDetailItem mSign;
    //求职状态
    @BindView(R.id.work_state)
    PersonalDetailItem mWorkState;
    //真实姓名
    @BindView(R.id.name)
    PersonalDetailItem mName;
    //学历
    @BindView(R.id.education)
    PersonalDetailItem mEducation;
    //现居地
    @BindView(R.id.live_place)
    PersonalDetailItem mLivePlace;
    //期望工作地
    @BindView(R.id.hope_place)
    PersonalDetailItem mHopePlace;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_info;
    }

    @Override
    protected void initSth() {
        super.initSth();
        CityPickerView.getInstance().init(this);
        mTopNavigation.setNavigationBarListener(this);
        showHumanInfo(mUid);

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED
                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(mActivity, new String[]{
                    Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            }, REQUEST_CODE_PERMISSION);
        } else {
            File file = new File(Environment.getExternalStorageDirectory(), "Pictures");
            if (!file.exists()) {
                if (!file.mkdir()) {
                    showToast("存储空间不足");
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            for (int grantResult : grantResults) {
                if (grantResult == PackageManager.PERMISSION_DENIED) {
                    showToast("拒绝权限可能导致某些功能无法正常使用");
                    return;
                }
            }
            File file = new File(Environment.getExternalStorageDirectory(), "Pictures");
            if (!file.exists()) {
                if (!file.mkdir()) {
                    showToast("存储空间不足");
                }
            }
        }
    }

    /**
     * 显示底部弹框
     *
     * @param key   key
     * @param items list
     */
    private void showBottomSheet(final String key, String... items) {
        QMUIBottomSheet.BottomListSheetBuilder builder = new QMUIBottomSheet.BottomListSheetBuilder(mActivity)
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        dialog.dismiss();
                        updateHumanInfo(mUid, key, String.valueOf(position + 1));
                        updateHumanInfo(mUid, key, String.valueOf(position + 1));
                    }
                });
        for (String item : items) {
            builder.addItem(item);
        }

        builder.build().show();
    }

    /**
     * 选择家乡、现居地、希望工作地
     *
     * @param key key
     */
    private void chooseCity(final String key) {
        CityPickerView.getInstance().setConfig(new CityConfig.Builder(this).build());
        CityPickerView.getInstance().setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {

                StringBuilder builder = new StringBuilder();
                //省份
                if (province != null) {
                    builder.append(province.getName());
                }

                //城市
                if (city != null) {
                    builder.append(city.getName());
                }

                //地区
                if (district != null) {
                    builder.append(district.getName());
                }
                updateHumanInfo(mUid, key, builder.toString());
            }

            @Override
            public void onCancel() {
            }
        });
        CityPickerView.getInstance().showCityPicker(this);
    }


    /**
     * 显示带输入框的对话框
     *
     * @param key       key
     * @param title     标题
     * @param hint      hint
     * @param inputType 输入类型
     */
    private void showEditDialog(final String key, String title, String hint, int inputType) {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(mContext);
        builder.getEditText().setFilters(new InputFilter[]{new InputFilterUtil.NoEmojiFilter()});
        builder.setTitle(title)
                .setPlaceholder(hint)
                .setInputType(inputType)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            if (key.equals("humanPhone") && !VerifyUtil.checkPhone(text.toString())) {
                                showToast("请输入正确手机号");
                                return;
                            }
                            updateHumanInfo(mUid, key, text.toString());
                        } else {
                            showToast("内容不能为空");
                        }
                    }
                })
                .show();
    }


    @OnClick({R.id.img_head, R.id.nick_name, R.id.phone, R.id.birth_date,
            R.id.hometown, R.id.sign, R.id.work_state, R.id.name, R.id.education,
            R.id.live_place, R.id.hope_place,R.id.sex})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_head:
                Matisse.from(mActivity)
                        .choose(MimeType.allOf())
                        .countable(false)
                        .capture(true)
                        .captureStrategy(
                                new CaptureStrategy(true, "com.qiuzhiyi.fileprovider"))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(new GlideEngine())
                        .forResult(REQUEST_CODE_CHOOSE);
                break;
            case R.id.nick_name:
                showEditDialog("humanQuestion", "更改昵称", "在此输入昵称", InputType.TYPE_CLASS_TEXT);
                break;
            case R.id.phone:
                showEditDialog("humanPhone", "更改手机号", "在此输入手机号", InputType.TYPE_CLASS_PHONE);
                break;
            case R.id.birth_date:
                DateDialog dateDialog = new DateDialog(mContext, new DateDialog.OnDateChooseListener() {
                    @Override
                    public void onDateChoose(String date) {
                        updateHumanInfo(mUid, "humanAnswer", date);
                    }
                });
                dateDialog.show();
                break;
            case R.id.hometown:
                chooseCity("humanAddress");
                break;
            case R.id.sign:
                showEditDialog("humanRemark", "更改签名", "在此输入签名", InputType.TYPE_CLASS_TEXT);
                break;
            case R.id.work_state:
                showBottomSheet("humanStatus", "正在求职", "已经工作");
                break;
            case R.id.name:
                showEditDialog("humanName", "更改姓名", "在此填写真实姓名", InputType.TYPE_CLASS_TEXT);
                break;
            case R.id.education:
                showBottomSheet("humanEducation", "大专", "本科", "硕士", "博士", "其他");
                break;
            case R.id.live_place:
                chooseCity("humanAddressCurr");
                break;
            case R.id.hope_place:
                chooseCity("humanAddressHope");
                break;
            case R.id.sex:
                chooseSex();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            String filePath = UriUtil.getRealPathFromUri(mContext, Matisse.obtainResult(data).get(0));
            up(filePath);
        }
    }


    /**
     * 异步处理
     *
     * @param filePath 文件路径
     */
    private void up(final String filePath) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(filePath, options);
                int normalWidth = options.outWidth;
                int width = TransformUtil.dp2px(mContext, 50);

                int sample = 1;
                if (normalWidth > width) {
                    sample = normalWidth / width;
                }
                if (sample <= 0) {
                    sample = 1;
                }
                options.inSampleSize = sample;
                options.inJustDecodeBounds = false;
                Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Pictures/head.jpg");
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
                String base = ImageUtil.bitmapToBase64(bitmap);
                e.onNext(base);
                e.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(String s) {
                        uploadPic(mUid, s);

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 显示用户信息
     *
     * @param uid 用户编号
     */
    private void showHumanInfo(String uid) {
        ObservableHelper.createObservable(RetrofitHelper.createService().showHumanInfo(uid))
                .subscribe(new SelectorObserver<BaseItem<HumanItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<HumanItem> humanItemBaseItem) {
                        HumanItem item = humanItemBaseItem.getObjValue();
                        setHumanInfo(item);
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog();
                    }
                });
    }

    /**
     * 设置用户信息
     *
     * @param item 用户对象
     */
    private void setHumanInfo(HumanItem item) {
        Glide.with(mContext)
                .load(item.getHumanPicUrl())
                .error(R.mipmap.icon)
                .into(mImgHead);
        mNickName.setTxtRight(item.getHumanQuestion());
        mSex.setTxtRight(item.getHumanSex().equals("1") ? "男" : "女");
        mPhone.setTxtRight(item.getHumanPhone());
        mBirthDate.setTxtRight(item.getHumanAnswer());
        mHometown.setTxtRight(item.getHumanAddress());
        mSign.setTxtRight(item.getHumanRemark());
        mWorkState.setTxtRight(transferWorkState(item.getHumanStatus()));
        mName.setTxtRight(item.getHumanName());
        mEducation.setTxtRight(transferEducation(item.getHumanEducation()));
        mLivePlace.setTxtRight(item.getHumanAddressCurr());
        mHopePlace.setTxtRight(item.getHumanAddressHope());
    }

    private String transferEducation(String num) {
        String education;
        switch (num) {
            case "1":
                education = "大专";
                break;
            case "2":
                education = "本科";

                break;
            case "3":
                education = "硕士";
                break;
            case "4":
                education = "博士";
                break;
            case "5":
                education = "其他";
                break;
            default:
                education = "";
                break;
        }
        return education;
    }

    private String transferWorkState(String num) {
        String workState;
        switch (num) {
            case "1":
                workState = "正在求职";
                break;
            case "2":
                workState = "已经工作";

                break;
            default:
                workState = "";
                break;
        }
        return workState;
    }

    /**
     * 更新用户信息
     *
     * @param uid   用户编号
     * @param key   更新字段
     * @param value 更新数据
     */
    private void updateHumanInfo(String uid, String key, String value) {
        Map<String, String> map = new HashMap<>();
        map.put("humanId", uid);
        map.put(key, value);
        ObservableHelper.createObservable(RetrofitHelper.createService().updateHumanInfo(map))
                .subscribe(new SelectorObserver<BaseItem<HumanItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<HumanItem> humanItemBaseItem) {
                        setHumanInfo(humanItemBaseItem.getObjValue());
                        HumanCache.saveHumanInfo(mContext, humanItemBaseItem.getObjValue());
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog("正在更新用户信息");
                    }
                });
    }


    /**
     * 上传图片
     *
     * @param uid 用户编号
     * @param pic base64
     */
    private void uploadPic(String uid, String pic) {
        Map<String, String> map = new HashMap<>();
        map.put("humanId", uid);
        map.put("humanPicUrl", pic);
        ObservableHelper.createObservable(RetrofitHelper.createService().updateHumanPic(map))
                .subscribe(new SelectorObserver<BaseItem<HumanItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<HumanItem> humanItemBaseItem) {
                        HumanCache.saveHumanInfo(mContext, humanItemBaseItem.getObjValue());
                        setHumanInfo(humanItemBaseItem.getObjValue());
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();

                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog("正在上传图片");
                    }
                });
    }

    private void chooseSex() {
        QMUIDialog.MenuDialogBuilder builder = new QMUIDialog.MenuDialogBuilder(mContext);
        builder.addItems(new String[]{"男", "女"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                updateHumanInfo(mUid, "humanSex", String.valueOf(which + 1));
            }
        });
        builder.create().show();
    }
}
